const { connectMongoDB, closeMongoDB } = require('./util')

// 登录DAO 根据username返回用户数据
const login = username => {
  return new Promise(async resolve => {
    const { client, dbo } = await connectMongoDB()
    dbo.collection('user').find({ username }).toArray((err, res) => {
      if (err) {
        throw err
      }
      resolve(res)
      closeMongoDB(client)
    })
  })
}

// 注销 - 根据username将cg设为null
const logout = username => {
  return new Promise(async resolve => {
    const {client, dbo} = await connectMongoDB()
    const where = { username }
    dbo.collection('user').updateOne(where, {
      $set: { cg: null }
    }).then(_res => {
      closeMongoDB(client)
      resolve()
    })
  })
}

module.exports = {
  login,
  logout
}